<?php

class VcardBlock extends BlockInstance {
	public $CI;
	
	public function __construct()
	{
		$this->CI =& get_instance();
	}
	
	public function __call($m, $a)
	{
		global $BBX;
		
		// Instantiate stuff
		$instance = $a[0]['data'];
		$content  = $a[1];
		
		$_data = $this->_get_data($instance, $content);
		if ($_data !== false)
		{
			$vcard = $_data;
			$name  = $vcard->name;
		}
		else
		{
			// Defaults!
			$vcard = new stdClass;
			$name  = $content->field1_value;
			$vcard->name = $content->field1_value;
		
			// Load up more vcard data, or prepopulate with content data
			$vcard->org		= '';
			$vcard->url 	= isset($content->data_url) ? $content->data_url : '';
			$vcard->email   = '';
			$vcard->addr	= isset($content->data_addr_str1) ? $content->data_addr_str1 : '';
			$vcard->city 	= isset($content->data_addr_city) ? $content->data_addr_city : '';
			$vcard->state	= isset($content->data_addr_state) ? $content->data_addr_state : '';
			$vcard->postal	= isset($content->data_addr_postal) ? $content->data_addr_postal : '';
			$vcard->country	= isset($content->data_addr_country) ? $content->data_addr_country : '';
			$vcard->phone	= '';
		}
		
		// Guess at the full name; assume 0: First, 1: Last[, 2: Middle]
		$name = split('/\s+/', $name);
		if (isset($name[0]))
			$vcard->given = $name[0];
		else
			$vcard->given = '';
		
		if (isset($name[2]))
			$vcard->middle = $name[2];
		else
			$vcard->middle = '';
		
		if (isset($name[1]))
			$vcard->family = $name[1];
		else
			$vcard->family = '';
		
		// Basic view data
		$data['inst'] 	  = $instance;
		$data['content']  = $content;
		$data['vcard']	  = $vcard;
		
		$this->CI->load->view('blocks/vcard/block', $data);
	}
	
	private function _get_data($inst, $content)
	{
		$inst_id = (int)($inst->id . $content->id);
		$query   = $this->CI->db->query("SELECT * FROM vcard_data WHERE instance_id = ? LIMIT 1", $inst_id);
		if ($query->num_rows() == 1)
			return $query->first_row();
		else
			return false;
	}
}

?>